package org.cnbi.web.controller.manage;


import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.tools.generic.NumberTool;
import org.cnbi.entity.Company;
import org.cnbi.entity.Menu;
import org.cnbi.entity.Role;
import org.cnbi.entity.User;
import org.cnbi.service.IHandleService;
import org.cnbi.service.ISystemService;
import org.cnbi.service.IUserService;
import org.cnbi.utils.date.DateUtil;
import org.cnbi.utils.json.JsonUtil;
import org.cnbi.utils.pagination.PagingUtil;
import org.cnbi.utils.pojo.MsgBean;
import org.cnbi.utils.pojo.SqlParamsBean;
import org.cnbi.utils.tools.ActionConstants;
import org.cnbi.utils.tools.Constants;
import org.cnbi.utils.tools.GlobalConstants;
import org.cnbi.utils.tools.StateConstants;
import org.cnbi.utils.tools.UserConstants;
import org.cnbi.web.controller.base.BaseController;
import org.cnbi.web.utils.ContextHolderUtils;
import org.cnbi.web.utils.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 用户操作Controller
 * Copyright © 2014中国经邦. All rights reserved.
 * @author zhh
 * @date 2014年4月28日下午11:14:04
 * @cnbi-web
 */
@Controller
@RequestMapping("/userM")
public class UserMController extends BaseController {
	
	private static final Log logger = LogFactory.getLog(UserMController.class);
	
	public static final NumberTool numTools = new NumberTool();
	
	@Autowired
	private IHandleService handleService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private ISystemService systemService;
	/**
	 * 用户查询 入口
	 * @param param 参数类
	 * @param menu 当前 菜单项
	 * @param user 用户
	 * @page 分页类
	 * **/
	@RequestMapping(value = "/index")
	public ModelAndView main(SqlParamsBean param,Menu menu,User user,PagingUtil page,
			HttpServletResponse response) {
		Object datas = queryUserList(page,user);
		ModelAndView view  = getReturnView(menu,response,datas);;
		if(user.getUsername() != null && user.getUsername().length() != 0){
			view.addObject("username", user.getUsername().replaceAll("%", ""));
		}
		
		return view;
	}
	
	/**
	 * 查询用户名 是否存在
	 * @param user 参数类
	 * return json数据
	 * **/
	@RequestMapping(value = "/queryUser")
	@ResponseBody
	public MsgBean queryUser(User user) {
		MsgBean msg = new MsgBean();
		String sqlIs = getSqlByKey(UserConstants.USERISNOT);
		/**
		 * 不为 0 时 ; 需要用户重新 输入用户名;
		 * **/
		int count = userService.queryIsNot(sqlIs,user);
		if(count > 0){
			msg.setFlag(false);
			msg.setText("该用户名已经存在;请重新输入...");
		}
		return msg;
	}
	
	
	/**
	 * 添加用户
	 * @param param 参数类
	 * @param menu 当前 菜单项
	 * @param user 用户
	 * @page 分页类
	 * **/
	@RequestMapping(value = "/addUser")
	public ModelAndView addUser(SqlParamsBean param,Menu menu,User user,PagingUtil page,
			HttpServletResponse response) {
		addUser(user);
		user.setUsername(null);
		Object datas = queryUserList(page,user);
		ModelAndView view = getReturnView(menu,response,datas);
		return view;
	}
	
	/**
	 * 修改用户
	 * @param param 参数类
	 * @param menu 当前 菜单项
	 * @param user 用户
	 * @page 分页类
	 * **/
	@RequestMapping(value = "/updateUser")
	public ModelAndView updateUser(SqlParamsBean param,Menu menu,User user,PagingUtil page,
			HttpServletResponse response) {
		updateUser(user);
		user.setUsername(null);
		Object datas = queryUserList(page,user);
		ModelAndView view = getReturnView(menu,response,datas);
		return view;
	}
	
	/**
	 * 删除用户
	 * @param param 参数类
	 * @param menu 当前 菜单项
	 * @param user 用户
	 * @page 分页类
	 * **/
	@RequestMapping(value = "/deleteUser")
	public ModelAndView deleteUser(SqlParamsBean param,Menu menu,User user,PagingUtil page,
			HttpServletResponse response,HttpServletRequest request) {
		deleteUser(user);
		user.setUsername(null);
		Object datas = queryUserList(page,user);
		ModelAndView view = getReturnView(menu,response,datas);
		
		return view;
	}
	
	/**
	 * @param menu
	 * @param datas
	 * @return view
	 * **/
	@SuppressWarnings("unchecked")
	private ModelAndView getReturnView(Menu menu,HttpServletResponse response,Object datas) {
		ModelAndView view = secondNavHandle(menu, response);
		view.addObject("pageBean", menu);
		setContentType(response, null);
		setContext(view);
		view.addObject(Constants.DATAS, datas);
		//公司列表
		List<Company> list= (List<Company>)  ContextHolderUtils.getServletContext().getAttribute(Constants.COMPANY+StateConstants.LIST);
		//角色列表
		List<Role> listRole = (List<Role>)  ContextHolderUtils.getServletContext().getAttribute(Constants.ROLE+StateConstants.LIST);
		view.addObject(Constants.COMPANY+StateConstants.LIST, list);
		view.addObject(Constants.ROLE+StateConstants.LIST, listRole);
		view.addObject(Constants.ROLE+StateConstants.MAP, (Map<String,String>) ContextHolderUtils.getServletContext().getAttribute(Constants.ROLE+StateConstants.MAP));
		logger.info("datas===>>>>"+JsonUtil.generateJson(datas));
		view.addObject("numTools", numTools);
		return view;
	}

	/**
	 * 查询  用户列表
	 * @param page PageUtil类  
	 * 		numPerPage 每页显示数
	 * 		currentPage 当前页码
	 * 		sql 分页sql语句
	 * @return Pagination 封转 分页以及数据 
	 * **/
	private Object queryUserList(PagingUtil page,User user) {
		String username = user.getUsername();
		String sql = getSqlByKey(UserConstants.USER+UserConstants.USERLIST);
		/*条件查询*/
		if(username != null && username.length() != 0){
			sql = getSqlByKey(UserConstants.USER+ActionConstants.QUERY);
			user.setUsername("%"+username+"%");
		}
		page.setSql(sql);
		return userService.queryList(page, user);
	}
	
	/**
	 * 添加用户
	 * @param user
	 * **/
	private void addUser(User user) {
		String sql = getSqlByKey(UserConstants.USERINSERT);
		//当前用户添加的 时间 
		user.setCreateTime(DateUtil.formatDate(Calendar.getInstance().getTime(), "yyyy/MM/dd hh:mm:ss"));
		//密码加密设置
		user.setPassword(PasswordUtil.encrypt(user.getUsername(), user.getPassword(), PasswordUtil.getStaticSalt()));
		userService.addUser(sql,user);
		systemService.addLog(getSqlByKey(ActionConstants.MANAGE + ActionConstants.ADD+"Log"),getSysLog("用户【" + user.getUsername()+ "】添加成功！", GlobalConstants.Log_Type_INSERT, GlobalConstants.Log_Leavel_INFO));
	}
	
	
	/**
	 * @ 修改用户
	 * @param user
	 * **/
	private void updateUser(User user) {
		String sql = getSqlByKey(UserConstants.USERUPDATE);
		userService.updateUser(sql, user);
		systemService.addLog(getSqlByKey(ActionConstants.MANAGE + ActionConstants.ADD+"Log"),getSysLog("用户【" + user.getUsername()+ "】修改成功！", GlobalConstants.Log_Type_UPDATE, GlobalConstants.Log_Leavel_INFO));
	}

	/**
	 * 删除用户
	 * @param user
	 * **/
	private void deleteUser(User user) {
		//删除关联表
		delRelation(user.getUsername());
		//用户表
		String sql = getSqlByKey(UserConstants.USER+ActionConstants.DEL);
		//spring mvc 参数未替换 :username --> '2','3'
		sql = getUserNameParam(sql,user.getUsername());
		
		userService.deleteUser(sql, null);
		systemService.addLog(getSqlByKey(ActionConstants.MANAGE + ActionConstants.ADD+"Log"),getSysLog("用户【" + user.getUsername()+ "】删除成功！", GlobalConstants.Log_Type_DEL, GlobalConstants.Log_Leavel_INFO));
	}
	
	/**
	 * sql 参数替换
	 * **/
	private static String  getUserNameParam(String sql,String username) {
		sql = sql.replaceAll(":username", username);
		return sql;
	}
	
	
	/**
	 * 删除 用户的关联表
	 * */
	private void delRelation(String username) {
		//用户公司表
		String sqlUC = getSqlByKey(UserConstants.DELETE_USER_COM);
		handleService.execute(getUserNameParam(sqlUC,username),null);
		//用户角色表
		String sqlUR = getSqlByKey(UserConstants.DELETE_USER_ROLE);
		handleService.execute(getUserNameParam(sqlUR,username),null);
	}
}
